<?php

namespace catchAdmin\community\controller;

use app\common\lib\Redis;
use app\common\model\PatientInfo as PatientModel;
use app\common\model\Relation as RelationModel;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use catchAdmin\community\request\CommunityRegisterRequest;
use think\exception\ValidateException;
use think\Request;

class CommunityRegister extends CatchController
{
    /**
     * 添加患者
     * @param Request $request
     * @return \think\response\Json
     */
    public function addCommunityPatient(Request $request): \think\response\Json
    {
        try {
            $req = $request->param();
            validate(CommunityRegisterRequest::class)->check($req);

            //性别字典
            $sex = config('dictionary.sex');

            $req['patientId'] = (string)$req['idno'];
            $req['idType'] = (string)$req['idType'];
            $req['idno'] = (string)$req['idno'];
            $req['sex'] = $sex[$req['sex']];
            $req['sourceType'] = 2;
            $req['deleted_at'] = 0;
            $req['created_ymd']  = date('Y-m-d');
            $req['created_time'] = date('Y-m-d H:i:s');

            if (!empty($req['relationType'])) {
                $req['relationType'] = (string)$req['relationType'];
            }

            //查看患者是否存在
            $patient = (new PatientModel())->where('patientId', (string)$req['idno'])->find();

            if (isset($patient) && !empty($patient)) {
                $ret = $patient->save($req);
            }else{
                $ret = (new PatientModel())->addData($req);
            }
            return CatchResponse::success($ret);
        } catch (ValidateException $exception) {
            throw new ValidateException($exception->getMessage());
        }
    }

    /**
     * 获取联系人关系
     * @return \think\response\Json
     */
    public function getCommunityRelation(): \think\response\Json
    {
        return CatchResponse::success((new RelationModel())->getDatas());
    }
}